<template>
	<!-- <view :class="{'pickerMask':visable}" @click="maskClick" @touchmove.stop.prevent="returnHandle">
		
	</view> -->

	<u-popup :maskCloseAble="true" mode="bottom" :popup="false" v-model="value" length="auto" @close="close"
		z-index="999">

		<cxView height="600" width="100vw" >

			<view class="operate-box" @touchmove.stop.prevent="returnHandle" @tap.stop="returnHandle">
				<cxView @confirm="close">取消</cxView>
				<cxView display="flex">共<cxView :color="themeColor">{{timeLengh}}</cxView>天</cxView>
				<view :style="{color:themeColor}" @click="pickerConfirm">确定</view>
			</view>
			<!-- 开始时间和结束时间 -->
			<cxView @tap.stop="returnHandle" display="flex" alignItems="center" height="80"
				justify-content="space-around" background="white">
				<!-- <view class="time-box"> -->
				<view @click="touchSelect(0)" class="time-item" :style="{color:touchIndex?'#000000':themeColor}">
					<cxView>{{startText}}</cxView>
					<cxView>{{resultDate[0]}}</cxView>
				</view>
				<text>至</text>
				<view @click="touchSelect(1)" class="time-item" :style="{color:touchIndex?themeColor:'#000000'}">
					<cxView>{{endText}}</cxView>
					<cxView>{{resultDate[1]}}</cxView>
				</view>
				<!-- </view> -->
			</cxView>

			<picker-view :value="pickerValue" @change="pickerChange" class="picker-view"
				:indicator-style="indicatorStyle" @tap.stop="returnHandle">
				<picker-view-column>
					<view class="picker-item" v-for="(item, index) in years" :key="index">{{item}}年</view>
				</picker-view-column>
				<picker-view-column>
					<view class="picker-item" v-for="(item, index) in months" :key="index">{{ item }}月</view>
				</picker-view-column>
				<picker-view-column v-if="days.length > 0">
					<view class="picker-item" v-for="(item, index) in days" :key="index">{{ item }}日</view>
				</picker-view-column>
			</picker-view>



		</cxView>


	</u-popup>

</template>
<script>
	/**
	 * 由https://github.com/JamyKing/uni-load-refresh此项目修改
	 * | ------ | ------ | ------ | ------ |
| visable | Boolean | false | 日期选择控件的显示/隐藏，注意使用`.sync`修饰符(true: 显示; false: 隐藏) |
| defaultDate | Array | [] | 默认预设值(比如:`['2021-06-01', '2021-07-01']`) |
| minYear | Number | 1990 | 最小年份 |
| timeLimit | Boolean | false | 日期区间限制(true: 限制结束日期`<=`当前日期; false: 不限制) |
| deferYear | Number | 0 | 年份选项顺延数，仅当`timeLimit`为`false`时生效(举个栗子: `deferYear = 1`, 则年份选项的最大值为: `当前年份 + deferYear`) |
| themeColor | String | #10BE9D | 选择框操作栏部分字体颜色 |
| startText | String | 开始时间 | 日期范围起始处文本 |
| endText | String | 结束时间 | 日期范围结束处文本 |

	 */
	export default {
		name: 'termPicker',
		props: {
			visable: {
				type: Boolean,
				default: false
			},
			defaultDate: {
				type: Array,
				default: () => []
			},
			minYear: {
				type: Number,
				default: 1990,
			},
			timeLimit: {
				type: Boolean,
				default: false
			},
			deferYear: {
				type: Number,
				default: 0,
			},
			themeColor: {
				type: String,
				default: '#f70'
			},
			startText: {
				type: String,
				default: '开始时间'
			},
			endText: {
				type: String,
				default: '结束时间'
			},
			// 通过双向绑定控制组件的弹出与收起
			value: {
				type: Boolean,
				default: false
			},
		},
		data() {
			const date = new Date();
			const years = [];
			const year = date.getFullYear();
			const months = [];
			const month = date.getMonth() + 1;
			const day = date.getDate();
			const maxYear = this.timeLimit ? year : year + this.deferYear
			for (let i = this.minYear; i <= maxYear; i++) {
				years.push(i);
			}
			for (let i = 1; i <= 12; i++) {
				months.push(i);
			}
			return {
				indicatorStyle: 'height: 100rpx;',
				touchIndex: 0,
				year,
				month,
				day,
				years,
				months,
				days: [],
				pickerValue: [],
				resultDate: [],
				timeLengh: 0
			};
		},
		watch: {
			// 在select弹起的时候，重新初始化所有数据
			value: {
				immediate: true,
				handler(val) {
					if (val) setTimeout(() => this.setDate(), 10);
				}
			},
		},


		mounted() {
			this.setDate()
		},
		methods: {
			returnHandle() {
				
			},
			setDate() {
				if (this.defaultDate.length > 0) {
					let date = this.defaultDate[0]
					this.resultDate = this.defaultDate
					this.setPicker(date)
				} else {
					let month = this.month < 10 ? '0' + this.month : this.month
					let day = this.day < 10 ? '0' + this.day : this.day
					let nowTime = this.year + '-' + month + '-' + day
					this.resultDate = [nowTime, nowTime]
					this.setPicker(nowTime)
				}
			},
			setPicker(date) {
				const splitVal = date.split('-')
				let year = this.years.indexOf(Number(splitVal[0]))
				let month = Number(splitVal[1]) - 1
				let day = Number(splitVal[2]) - 1
				this.pickerChange({
					detail: {
						value: [year, month, day]
					}
				})
			},
			touchSelect(val) {
				let date = this.resultDate[val]
				this.touchIndex = val
				this.setPicker(date)
			},
			getDateTime(date) {
				let year = this.years[date[0]]
				let month = this.months[date[1]]
				let day = this.days[date[2]]
				if (month < 10) {
					month = '0' + month
				}
				if (day < 10) {
					day = '0' + day
				}
				this.resultDate[this.touchIndex] = year + '-' + month + '-' + day
			},
			pickerChange(e) {
				const currents = e.detail.value
				if (currents[1] + 1 === 2) {
					this.days = []
					if (
						((currents[0] + this.minYear) % 4 === 0 &&
							(currents[0] + this.minYear) % 100 !== 0) ||
						(currents[0] + this.minYear) % 400 === 0
					) {
						for (let i = 1; i < 30; i++) {
							this.days.push(i)
						}
					} else {
						for (let i = 1; i < 29; i++) {
							this.days.push(i)
						}
					}
				} else if ([4, 6, 9, 11].some((item) => currents[1] + 1 === item)) {
					this.days = []
					for (let i = 1; i < 31; i++) {
						this.days.push(i)
					}
				} else if (
					[1, 3, 5, 7, 8, 10, 12].some((item) => currents[1] + 1 === item)
				) {
					this.days = []
					for (let i = 1; i < 32; i++) {
						this.days.push(i)
					}
				}
				this.pickerValue = currents
				this.getDateTime(currents)

				// console.log(this.resultDate);
				// console.log("-----------");
				// console.log(this.valDayLength(this.resultDate[0], this.resultDate[1]));

				this.timeLengh = this.valDayLength(this.resultDate[0], this.resultDate[1]);
				// if (this.timeLengh < 0) {
				// 	this.timeLengh = 0;
				// }
			},
			maskClick() {
				this.$emit('input', false);
			},
			pickerConfirm() {
				const {
					resultDate,
					timeLimit
				} = this
				let startTime = new Date(resultDate[0]).getTime()
				let endTime = new Date(resultDate[1]).getTime()
				let nowTime = timeLimit ? new Date().getTime() : endTime
				if (startTime <= endTime && endTime <= nowTime) {
					this.$emit('confirm', resultDate)
					this.$emit('input', false);
				} else {
					uni.showToast({
						title: '时间范围不正确！',
						icon: 'none'
					})
				}
			},
			valDayLength(oldDate, newDate) {
				var d1 = new Date(oldDate);
				var d2 = new Date(newDate);
				var days = d2.getTime() - d1.getTime();
				var time = parseInt(days / (1000 * 60 * 60 * 24));
				return time

			},
			// 关闭
			close() {
				this.$emit('input', false);
			},

		}
	}
</script>

<style lang="scss" scoped>
	.operate-box {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 18rpx 30rpx;
		background-color: #FFFFFF;
		text-align: center;
		font-size: 30rpx;
		border-bottom: 2rpx solid #e5e5e5;

		.time-box {
			width: 60%;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.time-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
			}
		}
	}


	.picker-show {
		transform: translateY(0);
	}

	.picker-view {
		width: 750rpx;
		height: 400rpx;
		background-color: #FFFFFF;

		.picker-item {
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			text-align: center;
		}
	}
</style>